package com.ruoyi.tagging.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.FourConstans;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.construction.domain.ConstructionSite;
import com.ruoyi.construction.mapper.ConstructionSiteMapper;
import com.ruoyi.modules.domain.SoilSiteInfo;
import com.ruoyi.modules.mapper.SoilSiteInfoMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.tagging.DisposalSiteAndProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @desc  处置场所和项目工地 对接北斗标注
 **/
@Service
public class DisposalSiteAndProjectServiceImpl implements DisposalSiteAndProjectService {


    @Autowired
    private SysDictDataMapper dictDataMapper;


    @Autowired
    private ConstructionSiteMapper constructionSiteMapper;

    @Autowired
    private SoilSiteInfoMapper soilSiteInfoMapper;

    /**
     *   通用登录
     */
    public String login(String username, String password) {

        String pass = Md5Utils.hash(password);
        String param ="userId="+username
                +"&password="+pass
                +"&onlyValidate=false";
        String s = HttpUtils.sendGet(FourConstans.BASE_URL + FourConstans.LOGIN_URL, param, "utf-8");
        System.out.println(s);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String sessionId = jsonObject.getString("sessionId");
        return sessionId;
    }


    /**
     *  从字段获取项目父分类id
     *  type 0.项目  1.处置场所
     */
    public String projectConstructionSiteParentId(String type){
        SysDictData dictData = new SysDictData();
        dictData.setDictType("beidou_feng_lei");
        if("0".equals(type)){
            // 项目工地 父分类id
            dictData.setDictLabel("projectConstructionSite");
        }else{
            // 处置场所父分类id
            dictData.setDictLabel("soilSiteInfo");
        }

        String dirId = null;
        List<SysDictData> list = dictDataMapper.selectDictDataList(dictData);
        if(list.size()>0){
            dirId = list.get(0).getDictValue();
        }
        return dirId;
    }


    /*项目工地 新增 对接北斗标注*/
    @Override
    public String inserConstructionSiteBeiDouTagging(ConstructionSite constructionSite) {

        String sessionId = login(FourConstans.USERNAME,FourConstans.PASSWORD);

        JSONObject json = this.getJSONObject(constructionSite);

        String dirId = projectConstructionSiteParentId("0");

//        beidou_feng_lei
//        String ss = new String(new JsonStringEncoder().quoteAsString((json.toString())));
        String ss = json.toString();
        String param =
                "name="+constructionSite.getName()
                        +"&dirId="+dirId // 动态从字典里取
                        +"&lng="+constructionSite.getLongitude()
                        +"&lat="+constructionSite.getLatitude()
                        +"&radius="+100
            +"&minZoom="+4
            +"&exts="+ss
//            +"&addFiles="+new ArrayList<>()
                        +"&addr="+constructionSite.getAddress()
                        +"&sessionId="+sessionId;
        String s = HttpUtils.sendPost(FourConstans.BASE_URL + FourConstans.ADD_POI_URL, param);
        System.out.println(s);
        return s;

    }


    /*项目工地 修改 对接北斗标注*/
    @Override
    public String updateConstructionSiteBeiDouTagging(ConstructionSite constructionSite) {

        String sessionId = login(FourConstans.USERNAME,FourConstans.PASSWORD);
        JSONObject json = this.getJSONObject(constructionSite);
        String dirId = projectConstructionSiteParentId("0");

        String ss = json.toString();
        String param =
                "oldPoiId="+constructionSite.getFourConstructionSiteId()+
                "&name="+constructionSite.getName()
                        +"&dirId="+dirId // 动态从字典里取
                        +"&lng="+constructionSite.getLongitude()
                        +"&lat="+constructionSite.getLatitude()
                        +"&radius="+100
                        +"&minZoom="+4
                        +"&exts="+ss
//            +"&addFiles="+new ArrayList<>()
                        +"&addr="+constructionSite.getAddress()
                        +"&sessionId="+sessionId;
        System.out.println("请求参数"+param);
        String s = HttpUtils.sendPost(FourConstans.BASE_URL + FourConstans.UPDATE_POI_URL, param);
        System.out.println(s);
        return s;

    }


    /*项目工地 删除 对接北斗标注*/
    @Override
    public String delConstructionSiteBeiDouTagging(String fourConstructionSiteId) {

        String sessionId = login(FourConstans.USERNAME,FourConstans.PASSWORD);

        String param ="oldPoiId="+fourConstructionSiteId+
                      "&sessionId="+sessionId;
        String s = HttpUtils.sendPost(FourConstans.BASE_URL + FourConstans.DEL_POI_URL, param);
        System.out.println(s);
        return s;

    }

    // 处置场所 新增北斗相关
    @Override
    public String insertSoilSiteInfoBeiDouTagging(SoilSiteInfo soilSiteInfo) {

        String sessionId = login(FourConstans.USERNAME,FourConstans.PASSWORD);
        JSONObject json = this.getSoilSiteInfoJSONObject(soilSiteInfo);

        String dirId = projectConstructionSiteParentId("1");

//        beidou_feng_lei
//        String ss = new String(new JsonStringEncoder().quoteAsString((json.toString())));
        String ss = json.toString();
        String param =
                "name="+soilSiteInfo.getSoilName()
                        +"&dirId="+dirId // 动态从字典里取
                        +"&lng="+soilSiteInfo.getLongitude()
                        +"&lat="+soilSiteInfo.getLatitude()
                        +"&radius="+100
                        +"&minZoom="+4
                        +"&exts="+ss
//            +"&addFiles="+new ArrayList<>()
                        +"&addr="+soilSiteInfo.getAddress()
                        +"&sessionId="+sessionId;
        String s = HttpUtils.sendPost(FourConstans.BASE_URL + FourConstans.ADD_POI_URL, param);
        System.out.println("处置场所 新增"+s);
        return s;
    }


    // 处置场所 修改北斗相关
    @Override
    public String updateSoilSiteInfoBeiDouTagging(SoilSiteInfo soilSiteInfo) {

        String sessionId = login(FourConstans.USERNAME,FourConstans.PASSWORD);
        JSONObject json = this.getSoilSiteInfoJSONObject(soilSiteInfo);

        String dirId = projectConstructionSiteParentId("1");

        String ss = json.toString();
        String param =
                "oldPoiId="+soilSiteInfo.getFourSoilSiteId()+
                        "&name="+soilSiteInfo.getSoilName()
                        +"&dirId="+dirId // 动态从字典里取
                        +"&lng="+soilSiteInfo.getLongitude()
                        +"&lat="+soilSiteInfo.getLatitude()
                        +"&radius="+100
                        +"&minZoom="+4
                        +"&exts="+ss
//            +"&addFiles="+new ArrayList<>()
                        +"&addr="+soilSiteInfo.getAddress()
                        +"&sessionId="+sessionId;
        String s = HttpUtils.sendPost(FourConstans.BASE_URL + FourConstans.UPDATE_POI_URL, param);
        System.out.println("处置场所 修改"+s);
        return s;
    }



    /*处置场所 删除 对接北斗标注*/
    @Override
    public String delSoilSiteInfoBeiDouTagging(String fourSoilSiteId) {

        String sessionId = login(FourConstans.USERNAME,FourConstans.PASSWORD);

        String param ="oldPoiId="+fourSoilSiteId+
                "&sessionId="+sessionId;
        String s = HttpUtils.sendPost(FourConstans.BASE_URL + FourConstans.DEL_POI_URL, param);
        System.out.println("处置场所删除"+s);
        return s;

    }




    // 处置场所数据封装
    private JSONObject getSoilSiteInfoJSONObject(SoilSiteInfo soilSiteInfo){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("province_code",soilSiteInfo.getProvinceCode()==null?null:soilSiteInfo.getProvinceCode());
        jsonObject.put("province_name",soilSiteInfo.getProvinceName()==null?null:soilSiteInfo.getProvinceName());
        jsonObject.put("city_code",soilSiteInfo.getCityCode()==null?null:soilSiteInfo.getCityCode());
        jsonObject.put("city_name",soilSiteInfo.getCityName()==null?null:soilSiteInfo.getCityName());
        jsonObject.put("area_code",soilSiteInfo.getAreaCode()==null?null:soilSiteInfo.getAreaCode());
        jsonObject.put("area_name",soilSiteInfo.getAreaName()==null?null:soilSiteInfo.getAreaName());
        jsonObject.put("town_name",soilSiteInfo.getTownName()==null?null:soilSiteInfo.getTownName());
        jsonObject.put("town_code",soilSiteInfo.getTownCode()==null?null:soilSiteInfo.getTownCode());
        // 处置场所名称
        jsonObject.put("name",soilSiteInfo.getSoilName()==null?null:soilSiteInfo.getSoilName());
        //详细地址
        jsonObject.put("address",soilSiteInfo.getAddress()==null?null:soilSiteInfo.getAddress());
        // 有效期开始日期
        jsonObject.put("start_date",soilSiteInfo.getStartDate()==null?null :soilSiteInfo.getStartDate());
        // 有效期结束日期
        jsonObject.put("end_date",soilSiteInfo.getEndDate()==null?null:soilSiteInfo.getEndDate());
        // 处置场所负责人
        jsonObject.put("manager",soilSiteInfo.getManager()==null?null:soilSiteInfo.getManager());
        // 负责人联系电话
        jsonObject.put("manager_phone",soilSiteInfo.getManagerPhone()==null?null:soilSiteInfo.getManagerPhone());

        // 处置场所类型(选择：1.砂石土场、2.土方土场、3.建筑垃圾土场、4.渣土土场、5.灰浆等流体土场、6.其他土场)

        jsonObject.put("category",this.getCategory(soilSiteInfo.getCategory()));
        // 备注
        jsonObject.put("remark",soilSiteInfo.getRemark()==null?null:soilSiteInfo.getRemark());

        return jsonObject;
    }

    /**
     *  处置场所类型
     */
    private  String   getCategory(String category){
        String name = null;
        switch (category) {
            case "1":
                name ="砂石土场";
                break;
            case "2":
                name ="土方土场";
                break;
            case "3":
                name ="建筑垃圾土场";
                break;
            case "4":
                name ="渣土土场";
                break;
            case "5":
                name ="灰浆等流体土场";
                break;
            case "6":
                name ="其他土场";
                break;
            default:
                name ="其它";
        }

        return name;
    }


    // 项目参数封装
    private JSONObject getJSONObject(ConstructionSite constructionSite) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("province_code",constructionSite.getProvinceCode()==null?null:constructionSite.getProvinceCode());
        jsonObject.put("province_name",constructionSite.getProvinceName()==null?null:constructionSite.getProvinceName());
        jsonObject.put("city_code",constructionSite.getCityCode()==null?null:constructionSite.getCityCode());
        jsonObject.put("city_name",constructionSite.getCityName()==null?null:constructionSite.getCityName());
        jsonObject.put("area_code",constructionSite.getAreaCode()==null?null:constructionSite.getAreaCode());
        jsonObject.put("area_name",constructionSite.getAreaName()==null?null:constructionSite.getAreaName());
        jsonObject.put("town_name",constructionSite.getTownName()==null?null:constructionSite.getTownName());
        jsonObject.put("town_code",constructionSite.getTownCode()==null?null:constructionSite.getTownCode());
        // 项目名称
        jsonObject.put("name",constructionSite.getName()==null?null:constructionSite.getName());
        //详细地址
        jsonObject.put("address",constructionSite.getAddress()==null?null:constructionSite.getAddress());
        // 工地类型字典：proj_type

        jsonObject.put("type",getConstructionSiteType(constructionSite.getType()));
        // 建设单位（选择）
        jsonObject.put("construction_unit",constructionSite.getConstructionUnit()==null?null:constructionSite.getConstructionUnit());
        // 施工单位
        jsonObject.put("construction_company",constructionSite.getConstructionCompany()==null?null:constructionSite.getConstructionCompany());
        // 有效期开始日期
        jsonObject.put("start_date",constructionSite.getStartDate()==null?null :constructionSite.getStartDate());
        // 有效期结束日期
        jsonObject.put("end_date",constructionSite.getEndDate()==null?null:constructionSite.getEndDate());
        // 申报人名字
        jsonObject.put("user_name",constructionSite.getUserName()==null?null:constructionSite.getUserName());
        // 工地负责人
        jsonObject.put("leader",constructionSite.getLeader()==null?null:constructionSite.getLeader());
        // 工地负责人联系电话
        jsonObject.put("leader_phone",constructionSite.getLeaderPhone()==null?null:constructionSite.getLeaderPhone());
        // 出土垃圾类型（选择：1.未知、2.普通渣土、3.砂石、4.建筑废料、5.盾构土、6.拆除垃圾、7.装潢垃圾、8.其他）
//        jsonObject.put("cargo_type",constructionSite.getCargoType()==null?null:constructionSite.getCargoType());
        // 出土垃圾名称
        jsonObject.put("cargo_name",constructionSite.getCargoName()==null?null:constructionSite.getCargoName());
        // 备注
        jsonObject.put("remark",constructionSite.getRemark()==null?null:constructionSite.getRemark());
        return jsonObject;
    }

    /**
     *  处置场所类型
     *
     *  房屋建筑工地
     * 拆迁土地
     * 收储工地
     * 绿化园林工地
     * 市政道路工地
     * 地铁市政工地
     * 企业建筑工地
     * 房屋装修
     *
     * proj_type
     */
    private  String   getConstructionSiteType(String category){
        String name = null;
        switch (category) {
            case "1":
                name ="房屋建筑工地";
                break;
            case "2":
                name ="拆迁土地";
                break;
            case "3":
                name ="收储工地";
                break;
            case "4":
                name ="绿化园林工地";
                break;
            case "5":
                name ="市政道路工地";
                break;
            case "6":
                name ="地铁市政工地";
                break;
            case "7":
                name ="企业建筑工地";
                break;
            case "8":
                name ="房屋装修";
                break;
            default:
                name ="其它";
        }

        return name;
    }


    /**
     *  同步项目和场所id
     *  住建局
     */
    @Override
    public void changeId() {
        String sessionId = login(FourConstans.USERNAME,FourConstans.PASSWORD);
        String param ="sessionId="+sessionId;
        String s = HttpUtils.sendGet(FourConstans.BASE_URL + FourConstans.GET_POIS_URL, param, "utf-8");
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONArray jsonArray = jsonObject.getJSONArray("list");

        List<ConstructionSite> constructionSiteList = new ArrayList<>();
        List<SoilSiteInfo> siteInfoList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = JSONObject.parseObject(jsonArray.get(i)+"");
            // pid 2.施工工地    3.处置场所
            String pid = object.getString("pid");
            String name = object.getString("name");
            String id = object.getString("id");

            if("2".equals(pid)) {
                ConstructionSite constructionSite = new ConstructionSite();
                constructionSite.setName(name);
                constructionSite.setFourConstructionSiteId(id);
                constructionSiteList.add(constructionSite);
            }

            if("3".equals(pid)) {
                SoilSiteInfo siteInfo = new SoilSiteInfo();
                siteInfo.setSoilName(name);
                siteInfo.setFourSoilSiteId(id);
                siteInfoList.add(siteInfo);
            }

        }

        siteInfoList.forEach(it->{
            SoilSiteInfo siteInfo = new SoilSiteInfo();
            siteInfo.setSoilName(it.getSoilName());
            List<SoilSiteInfo> siteInfoList1 = soilSiteInfoMapper.selectSoilSiteInfoList(siteInfo);
            if(siteInfoList1.size()>0){
                SoilSiteInfo nn = new SoilSiteInfo();
                nn.setFourSoilSiteId(it.getFourSoilSiteId());
                nn.setId(siteInfoList1.get(0).getId());
                soilSiteInfoMapper.updateSoilSiteInfo(nn);
            }

            System.out.println("siteInfoList1========"+siteInfoList1.size());
        });

        constructionSiteList.forEach(it->{
            ConstructionSite constructionSite = new ConstructionSite();
            constructionSite.setName(it.getName());
            List<ConstructionSite> siteInfoList1 = constructionSiteMapper.selectConstructionSiteList(constructionSite);
            if(siteInfoList1.size()>0){
                ConstructionSite nn = new ConstructionSite();
                nn.setFourConstructionSiteId(it.getFourConstructionSiteId());
                nn.setId(siteInfoList1.get(0).getId());
                System.out.println("siteInfoList1========"+siteInfoList1.size());
                constructionSiteMapper.updateConstructionSite(nn);
            }

        });



    }

}
